package com.fanyouzhao.ehome2.admin.interceptor;


import com.fanyouzhao.ehome2.admin.annotation.NeedsLog;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author: fanyouzhao
 * @date: 10:52 2021/6/23
 */
public class LogInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        if (o instanceof HandlerMethod){
            // 通过HandlerMethod类型获取参数o的方法特征，获取Method方法
            Method method = ((HandlerMethod) o).getMethod();
            // 通过对象o获取Handler所在控制器的Class
            Class<?> clazz = ((HandlerMethod) o).getBeanType();
            boolean annoFromMethod = method.isAnnotationPresent(NeedsLog.class);
            boolean annoFromType = clazz.isAnnotationPresent(NeedsLog.class);
            // 判断Class类或者方法上有无NeedsLog注解
            if (annoFromMethod||annoFromType) {
                System.out.println("method.getName() = " + method.getName());
                System.out.println("method.getParameters() = " + method.getParameters());
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
